package downstream

import (
	"context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/status"
	"mall/api/promotion"
	"mall/internal/conf"
	"mall/internal/constant"
	"mall/pkg/ecode"
	"mall/pkg/log"
	"mall/pkg/network"
	"mall/pkg/request_key"
	"time"
)

func newPromotionClient(ctx context.Context, addr string) (
	client promotion.OffOpServiceClient, err error) {
	var conn *grpc.ClientConn
	conn, err = grpc.Dial(addr, grpc.WithInsecure(),
		grpc.WithUnaryInterceptor(network.ClientInterceptor(
			"bilin_promotion", time.Second*3, promotionErrorTranslator)))
	if err != nil {
		err = ecode.AppendMessage(constant.ErrRemoteError, "促销服务地址无法建立有效连接, err=%s", err.Error())
		log.FromContext(ctx).Warnw(err.Error())
		return
	}
	client = promotion.NewOffOpServiceClient(conn)
	return
}

func promotionErrorTranslator(err error) (errCode *ecode.ErrorCode) {
	errCode = ecode.AppendMessage(
		constant.ErrRemoteError, "比邻促销服务调用失败：%s", status.Convert(err).Message())
	return
}

func (d *Downstream) SubmitPromotion(ctx context.Context, sgId uint32, memberId uint64, bizNo string,
	orders []*promotion.TransactOrderEntity) (resp *promotion.LockTransactionRes, err error) {
	if d.promotionClient == nil {
		if d.promotionClient, err = newPromotionClient(
			ctx, conf.Conf.Downstream.PromotionAddress); err != nil {
			return
		}
	}
	clientCtx, cancel := request_key.NewOutGoingContext(ctx, time.Second*3)
	defer cancel()
	if resp, err = d.promotionClient.LockTransaction(clientCtx, &promotion.LockTransactionReq{
		BrandId:       int64(sgId),
		MemberId:      int64(memberId),
		OutTransNo:    bizNo,
		TransactScene: "ordering",
		Orders:        orders,
	}); err != nil {
		return
	}
	return
}
